//
//  NineViewController.m
//  jinling
//
//  Created by mac on 2018/9/21.
//  Copyright © 2018年 mac. All rights reserved.
//

#import "NineViewController.h"
#import <WebKit/WebKit.h>
#import <JavaScriptCore/JavaScriptCore.h>

@interface NineViewController ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler>
@property (strong, nonatomic) WKWebView *myWebView;
@property(nonatomic,strong)kongBaiye *kongBai;

@end

@implementation NineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    WKWebViewConfiguration* configuration = [[NSClassFromString(@"WKWebViewConfiguration") alloc] init];
    
    configuration.processPool = [WKProcessPool sharedProcessPool];
    [configuration.userContentController addScriptMessageHandler:self name:@"push"];
    [configuration.userContentController addScriptMessageHandler:self name:@"logout"];
    [configuration.userContentController addScriptMessageHandler:self name:@"back"];
    
    if ([_url containsString:@"modify-head-face.html"]) {
        
        self.myWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, _mainW, _mainH) configuration:configuration];
    }else{
        
        self.myWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, NAV_HEIGHT, _mainW, _mainH-NAV_HEIGHT) configuration:configuration];
    }
    
    
    self.myWebView.navigationDelegate = self;
    self.myWebView.UIDelegate=self;
    [self.view addSubview:self.myWebView];
    
    
    if ([_url containsString:@"modify-head-face.html"]) {
        self.progressView = [[UIProgressView alloc]initWithFrame:CGRectMake(0, iPhoneX ? 48.f : 20.f, CGRectGetWidth(self.view.frame), 2) ];
        
    }
    else{
        self.progressView = [[UIProgressView alloc]initWithFrame:CGRectMake(0, NAV_HEIGHT, CGRectGetWidth(self.view.frame), 2) ];
        
    }
    self.progressView.progressTintColor =_backgroundColor;
    [self.view addSubview:self.progressView];
    
    [self.myWebView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
    
    [self.myWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
    
    //    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
}

-(void)viewWillDisappear:(BOOL)animated{
    self.navigationController.navigationBarHidden=NO;
}
-(void)viewWillAppear:(BOOL)animated{
    
    
    if ([_url containsString:@"modify-head-face.html"]) {
        self.navigationController.navigationBarHidden=YES;
    }
    NSDictionary *userDic = [NSKeyedUnarchiver unarchiveObjectWithFile:_userModelFile];
    
    if (userDic!=nil) {
        NSString *oppenid=[userDic objectForKey:@"oppenid"];
        NSString *user_account=[userDic objectForKey:@"user_account"];
        if ([_url containsString:@"?"]){
            _url=[NSString stringWithFormat:@"%@&oppen_id=%@&user_account=%@",_url,oppenid,user_account];
        }
        else{
            _url=[NSString stringWithFormat:@"%@?oppen_id=%@&&user_account=%@",_url,oppenid,user_account];
        }
        
    }
    NSLog(@"%@",[NSString stringWithFormat:@"%@/%@",_addressUrl,_url]);
    NSString *urlStr=[NSString stringWithFormat:@"%@/%@",_addressUrl,_url];
    urlStr=[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlStr];
    
    NSMutableURLRequest *mutableRequest = [NSMutableURLRequest requestWithURL:url];
    
    [self.myWebView loadRequest:mutableRequest];
    
  
}
#pragma mark KVO的监听代理
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    //加载进度值
    if ([keyPath isEqualToString:@"title"]){//网页title
        if (object == self.myWebView){
            self.navigationItem.title = self.myWebView.title;
            if ([self.myWebView.title isEqualToString:@"会员登录" ]) {
                [_kongBai shanChu];
                _kongBai=[kongBaiye new];
                [self.view addSubview:_kongBai];
                [_kongBai mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.right.bottom.mas_equalTo(0);
                    make.top.mas_equalTo(0);
                }];
                [_kongBai creatView];
                _kongBai.customSelectedBlock  = ^{
                    _loginWithVc(self);
                };
                
            }
            
            else{
                [_kongBai shanChu];
            }
        }
        else{
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
        
    }
    else if ([keyPath isEqual:@"estimatedProgress"] && object == self.myWebView) {
        [self.progressView setAlpha:1.0f];
        [self.progressView setProgress:self.myWebView.estimatedProgress animated:YES];
        if (self.myWebView.estimatedProgress  >= 1.0f) {
            [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
                [self.progressView setAlpha:0.0f];
            } completion:^(BOOL finished) {
                [self.progressView setProgress:0.0f animated:YES];
            }];
        }
    }
    else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    
    if ([message.name isEqualToString:@"push"]) {
        
        NSDictionary *userDic = [NSKeyedUnarchiver unarchiveObjectWithFile:_userModelFile];
        if (userDic!=nil) {
            if ([message.body containsString:@"goodsdetail.html"]) {
                NSString *user_id_number_state=[userDic objectForKey:@"user_id_number_state"];
                if (user_id_number_state.integerValue==0) {
                    shiMingViewController *shiming=[[shiMingViewController alloc] init];
                    shiming.cengsu=_cengsu+1;
                    shiming.isHave=YES;
                    shiming.url=@"page/id_number.html";
                    [gongju pushNextViewController:self andRootController:shiming];
                    return;
                }
            }
        }

        if ([message.body containsString:@"page/index"]) {
            self.navigationController.tabBarController.selectedIndex=0;
            [self.navigationController popToRootViewControllerAnimated:YES];
            return;
            
        }
        
        if ([message.body isEqualToString:@"logout"]) {
            NSFileManager *defaultManager = [NSFileManager defaultManager];
            if ([defaultManager removeItemAtPath:_userModelFile error:nil]) {
                [self.navigationController popToRootViewControllerAnimated:YES];
            }
            return;
        }
        if ([message.body containsString:@"denglu"]) {
            _loginWithVc(self);
            return;
        }
        
        if ([message.body containsString:@"back"]) {
            [self.navigationController popViewControllerAnimated:YES];
            return;
        }
        if ([message.body containsString:@"member-center"]) {
            [self.navigationController popViewControllerAnimated:YES];
            return;
        }
        
        if (_cengsu==1) {
            TWOViewController *two=[[TWOViewController alloc] init];
            two.url=message.body;
            two.cengsu=_cengsu+1;
            two.isHave=YES;
            [gongju pushNextViewController:self andRootController:two];
        }
        if (_cengsu==2) {
            ThreeViewController *two=[[ThreeViewController alloc] init];
            two.url=message.body;
            two.cengsu=_cengsu+1;
            two.isHave=YES;
            [gongju pushNextViewController:self andRootController:two];
        }
        if (_cengsu==3) {
            FourViewController *two=[[FourViewController alloc] init];
            two.url=message.body;
            two.cengsu=_cengsu+1;
            two.isHave=YES;
            [gongju pushNextViewController:self andRootController:two];
        }
        if (_cengsu==4) {
            FiveViewController *two=[[FiveViewController alloc] init];
            two.url=message.body;
            two.cengsu=_cengsu+1;
            two.isHave=YES;
            [gongju pushNextViewController:self andRootController:two];
        }
        if (_cengsu==5) {
            SixViewController *two=[[SixViewController alloc] init];
            two.url=message.body;
            two.cengsu=_cengsu+1;
            two.isHave=YES;
            [gongju pushNextViewController:self andRootController:two];
        }
        if (_cengsu==6) {
            SevenViewController *two=[[SevenViewController alloc] init];
            two.url=message.body;
            two.cengsu=_cengsu+1;
            two.isHave=YES;
            [gongju pushNextViewController:self andRootController:two];
        }
        if (_cengsu==7) {
            EightViewController *two=[[EightViewController alloc] init];
            two.url=message.body;
            two.cengsu=_cengsu+1;
            two.isHave=YES;
            [gongju pushNextViewController:self andRootController:two];
        }
        if (_cengsu==8) {
            NineViewController *two=[[NineViewController alloc] init];
            two.url=message.body;
            two.cengsu=_cengsu+1;
            two.isHave=YES;
            [gongju pushNextViewController:self andRootController:two];
        }
        if (_cengsu==9) {
            TenViewController *two=[[TenViewController alloc] init];
            two.url=message.body;
            two.cengsu=_cengsu+1;
            two.isHave=YES;
            [gongju pushNextViewController:self andRootController:two];
        }
    }
    else if([message.name isEqualToString:@"back"]){
        [self.navigationController popViewControllerAnimated:YES];
    }
    else if([message.name isEqualToString:@"out"]){
        NSFileManager *defaultManager = [NSFileManager defaultManager];
        if ([defaultManager removeItemAtPath:_userModelFile error:nil]) {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    }
}


-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{


//    [MBProgressHUD hideHUDForView:self.view animated:YES];
    [self.progressView setProgress:0.0f animated:YES];

}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    
    
    NSString *url = navigationAction.request.URL.absoluteString;
    
    
    if ([url containsString:@"page/index"]){
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
    
    else if ([url containsString:@"oodsdetail.html"]){
        
        UIBarButtonItem *pulishButton2=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"购物车3"] style:UIBarButtonItemStylePlain target:self action:@selector(pushToGouWu)];
        
        
        UIBarButtonItem *pulishButton3=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"分享"] style:UIBarButtonItemStylePlain target:self action:@selector(pushTofenXiang)];
        
        [self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:pulishButton3,pulishButton2,nil]];
        
    }
    
    WKNavigationResponsePolicy actionPolicy = WKNavigationResponsePolicyAllow;
    //这句是必须加上的，不然会异常
    decisionHandler(actionPolicy);
}



-(void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    
    completionHandler();
}

-(void)pushToGouWu{
    if (_cengsu==1) {
        TWOViewController *two=[[TWOViewController alloc] init];
        two.url=@"page/shopping-cart.html";
            two.cengsu=_cengsu+1;
      two.isHave=YES;
        [gongju pushNextViewController:self andRootController:two];
    }
    if (_cengsu==2) {
        ThreeViewController *two=[[ThreeViewController alloc] init];
        two.url=@"page/shopping-cart.html";
            two.cengsu=_cengsu+1;
      two.isHave=YES;
        [gongju pushNextViewController:self andRootController:two];
    }
    if (_cengsu==3) {
        FourViewController *two=[[FourViewController alloc] init];
        two.url=@"page/shopping-cart.html";
            two.cengsu=_cengsu+1;
      two.isHave=YES;
        [gongju pushNextViewController:self andRootController:two];
    }
    if (_cengsu==4) {
        FiveViewController *two=[[FiveViewController alloc] init];
        two.url=@"page/shopping-cart.html";
            two.cengsu=_cengsu+1;
      two.isHave=YES;
        [gongju pushNextViewController:self andRootController:two];
    }
    if (_cengsu==5) {
        SixViewController *two=[[SixViewController alloc] init];
        two.url=@"page/shopping-cart.html";
            two.cengsu=_cengsu+1;
      two.isHave=YES;
        [gongju pushNextViewController:self andRootController:two];
    }
    if (_cengsu==6) {
        SevenViewController *two=[[SevenViewController alloc] init];
        two.url=@"page/shopping-cart.html";
            two.cengsu=_cengsu+1;
      two.isHave=YES;
        [gongju pushNextViewController:self andRootController:two];
    }
    if (_cengsu==7) {
        EightViewController *two=[[EightViewController alloc] init];
        two.url=@"page/shopping-cart.html";
            two.cengsu=_cengsu+1;
      two.isHave=YES;
        [gongju pushNextViewController:self andRootController:two];
    }
    if (_cengsu==8) {
        NineViewController *two=[[NineViewController alloc] init];
        two.url=@"page/shopping-cart.html";
            two.cengsu=_cengsu+1;
      two.isHave=YES;
        [gongju pushNextViewController:self andRootController:two];
    }
    if (_cengsu==9) {
        TenViewController *two=[[TenViewController alloc] init];
        two.url=@"page/shopping-cart.html";
            two.cengsu=_cengsu+1;
      two.isHave=YES;
        [gongju pushNextViewController:self andRootController:two];
    }
    
    
}
-(void)pushTofenXiang{
    
    FenXiangView *fenxiang=[FenXiangView new];
    [self.view addSubview:fenxiang];
    [fenxiang mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.mas_equalTo(0);
    }];
    fenxiang.themID=[NSString stringWithFormat:@"%@/%@",_addressUrl,_url];
    fenxiang.kLinkTitle=self.myWebView.title;
    fenxiang.kLinkDescription=@"";
    [fenxiang creatView];
}

- (void)dealloc {
    [self.myWebView removeObserver:self forKeyPath:@"title"];
    [self.myWebView removeObserver:self forKeyPath:@"estimatedProgress"];
}


- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {
    
    completionHandler(NO);
}


//可以识别多个手势
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
